package com.xr.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xr.blog.dao.BlogArticleTagMapper;
import com.xr.blog.pojo.BlogArticleTag;
import com.xr.blog.service.BlogArticleTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class BlogArticleTagServiceImpl extends ServiceImpl<BlogArticleTagMapper, BlogArticleTag> implements BlogArticleTagService {
    @Autowired
    BlogArticleTagMapper blogArticleTagMapper;

    @Override
    @Transactional(rollbackFor = Throwable.class,timeout = 10)
    public boolean saveBatch(Long articleId, List<Long> tagIds) {
        remove(new QueryWrapper<BlogArticleTag>().eq("article_id",articleId).notIn("tag_id",tagIds));
        List<BlogArticleTag> oldArticleTags=list(new QueryWrapper<BlogArticleTag>().eq("article_id",articleId));
        oldArticleTags.forEach(articleTag -> tagIds.remove(articleTag.getTagId()));
        if(!tagIds.isEmpty()){
            List<BlogArticleTag> articleTags=tagIds.stream().map(tagId -> new BlogArticleTag(articleId,tagId)).collect(Collectors.toList());
            return saveBatch(articleTags);
        }
        return true;
    }
}